from rqalpha.apis import *
import time
from rqalpha.environment import Environment
from rqalpha.my_factors.book import BookImblance
from rqalpha.my_factors.reform_data import reform_factor_data
from collections import OrderedDict
from rqalpha.const import ORDER_STATUS

config = {
    "base": {
        "start_date": "2021-07-31",
        "end_date": "2021-07-31",
        "frequency": "tick",
        "accounts": {
            "stock": 100000
        }
    },

    "extra": {
        "log_level": "info",
    },

    "mod": {
        "my_backtest": {
            "enabled": True
        },
        "sys_analyser": {
            "enabled": True,
            "benchmark": "000300.XSHG",
            "plot": True,
            "report_save_path": "C:\\Users\\huajia\Desktop\\rqalpha3\\rqalpha\\plot_result"
        },
        "sys_simulation": {
            "matching_type": "best_own",
        },
        "sys_accounts": {
            "validate_stock_position": False,
            "stock_t1": False
        }
    }
}


# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
def init(context):
    logger.info("init")
    # 已经做了米筐可以识别的symbol
    _env = Environment.get_instance()
    symbol = _env.config.base.symbol
    context.s1 = symbol
    update_universe(context.s1)
    # 是否已发送了order
    subscribe(context.s1)
    context.order_count = 1
    context.fired = False
    # subscribe_event(EVENT.POST_TICK, post_tick_handler)


def before_trading(context):
    print('before trading---------------')


# 你选择的证券的数据更新将会触发此段逻辑，例如日或分钟历史数据切片或者是实时数据切片更新
# def handle_bar(context, bar_dict):
def handle_tick(context, tick):
    # 开始编写你的主要的算法逻辑
    # print('handle tick--------------------')
    # bar_dict[order_book_id] 可以拿到某个证券的bar信息
    # context.portfolio 可以拿到现在的投资组合状态信息
    _env = Environment.get_instance()
    # 使用order_shares(id_or_ins, amount)方法进行落单
    # print(tick.order_book_id, context.now)
    # TODO: 开始编写你的算法吧！
    # print(tick.asks[0])
    # a1_price = tick.asks[0]
    # time.sleep(500)
    if not context.fired:
        # order_percent并且传入1代表买入该股票并且使其占有投资组合的100%
        # order_percent(context.s1, -1)
        price = tick.asks[0]
        print(tick.asks[0], tick.bids[0])
        order_shares(context.s1, -100, style=LimitOrder(12.9))
        # order_shares(context.s1, -100)
        context.fired = True





    # time.sleep(5)
    # order_percent并且传入1代表买入该股票并且使其占有投资组合的100%
    # order_percent(context.s1, -1)
    # price = tick.asks[0]
    # order_shares(context.s1, -100, style=LimitOrder(price))
    # order_shares(context.s1, -100)
    context.fired = True


def after_trading(context):
    print('after trading----------------')
    context.order_count = 1
